#coding=utf-8
import httplib2

class RTPrice(object):
    '''实时价格(realtime price)'''
    def __init__(self,code=None):
                self.code=code

                self.date='1970-01-01'
                self.time='00:00:00'

                self.open = 0.0
                self.jump = 0.0
                self.now = 0.0
                self.change = 0.0

                self.highest = 0.0
                self.lowest = 0.0

                self.volume = 0
                self.amount = 0

                self.bid_buy = 0.0
                self.bid_sale = 0.0

                self.slot_buy=[]
                self.slot_sale=[]

class NoWebPageError(Exception):
    def __init__(self, url):
        self.url = url
    def __str__(self):
        return "Cannot get the web page from %s."%self.url

class NoPriceError(Exception):
    def __init__(self, code, time_):
        self.code = code
        self.time = time_

    def __str__(self):
        return "%s: no Price Data on %s"%(self.code, self.time)

def get_page(url, encoding='gb18030', try_times=10, timeout=15):

    h = httplib2.Http(timeout=timeout)

    for i in range(try_times):
        try:
            resp, content = h.request(url)
        except Exception, e:
            print e
        else:
            if resp.status != 200:
                print 'status:',resp.status
                continue
            '''
            if resp['content-type'] and not resp['content-type'].startswith('text'):
                print 'content-type:',resp['content-type']
                continue
            '''
            htmltext = content.decode(encoding, 'ignore').encode('u8')

            return htmltext

    raise NoWebPageError(url)

url = "http://hq.sinajs.cn/list=%s"

def get_p_by_row(row):

    import datetime as dt
    now = dt.datetime.now().isoformat()

    s = row

    i = s.find('=')
    code = s[i-6: i]
    rp = RTPrice(code)

    try:
        start = s.find('"') + 1
        s = s[start:]
        end = s.find('"')
        s = s[:end]

        data = s.split(',')[1:]

        rp.open = float( data[0] )
        rp.now = float( data[2] )

        pre_close = float(data[1])
        rp.change = (rp.now - pre_close)/pre_close *100
        rp.jump = (rp.open - pre_close)/pre_close *100

        rp.highest = float( data[3] )
        rp.lowest = float( data[4] )
        rp.bid_buy = float( data[5] )
        rp.bid_sale = float( data[6] )
        rp.volume = int( data[7] )
        rp.amount = int( float(data[8]) )

        for i in range(0, 10, 2):
            rp.slot_buy.append([ float(data[10+i]), int(data[9+i])])
            rp.slot_sale.append([ float(data[20+i]),int(data[19+i])])

        rp.date = data[-2]
        rp.time = data[-1]

    except:
        raise NoPriceError(code, now)
    return rp

def get_rtprice(mcode):

    u = url%mcode
    s = get_page(u)

    try:
        data = get_p_by_row(s)
    except NoPriceError:
        return None
    return data

def get_rtprices(mcodes):
    n = len(mcodes)/100 + 1
    rs = []

    for i in range(n):
        cs = mcodes[i*100: (i+1)*100]

        u = ','.join(cs)
        u2 = url%u
        #print u2
        ss = get_page(u2).strip()

        for s in ss.split(';')[:-1]:
            s = s.strip()
            try:
                data = get_p_by_row(s)
            except NoPriceError, e:
                print e
            else:
                rs.append(data) 
